package com.example.util;

import com.example.entity.PushProcess;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;

/**
 * @Description
 * @Author Moran
 * @Date 2023-05-31 21:56
 */
@Component
public class PushUtil {
    private Logger log = LoggerFactory.getLogger(PushUtil.class);
    @Resource
    private RestTemplate restTemplate;

    /**
     * 推送数据
     */
    public boolean sendRecord(PushProcess pushProcess) {
        long startTime = System.currentTimeMillis();
        log.info("调用第三方接口开始：{}", LocalDateTime.now());
        String url = "http://localhost:8005/accept/process";
        ResponseEntity<String> responseBody = restTemplate.postForEntity(url, pushProcess, String.class);
        String body = responseBody.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(body);
            int code = jsonNode.get("code").asInt();
            if (code == 200) {
                log.info("调用第三方接口结束：{}", LocalDateTime.now());
                log.info("Total Use: " + (System.currentTimeMillis() - startTime) + "ms!");
                return true;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return true;
    }

}
